<template>
  <div class="monitor-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>系统监控</h3>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
            <el-button type="success" @click="exportReport">
              <el-icon><Download /></el-icon>
              导出报告
            </el-button>
          </div>
        </div>
      </template>

      <!-- 系统概览 -->
      <div class="overview-section">
        <h4>系统概览</h4>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-number">{{ systemStats.onlineUsers }}</div>
                <div class="overview-label">在线用户</div>
                <div class="overview-trend" :class="systemStats.userTrend > 0 ? 'up' : 'down'">
                  <el-icon><ArrowUp v-if="systemStats.userTrend > 0" /><ArrowDown v-else /></el-icon>
                  {{ Math.abs(systemStats.userTrend) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-number">{{ systemStats.totalRequests }}</div>
                <div class="overview-label">今日请求</div>
                <div class="overview-trend" :class="systemStats.requestTrend > 0 ? 'up' : 'down'">
                  <el-icon><ArrowUp v-if="systemStats.requestTrend > 0" /><ArrowDown v-else /></el-icon>
                  {{ Math.abs(systemStats.requestTrend) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-number">{{ systemStats.avgResponseTime }}ms</div>
                <div class="overview-label">平均响应时间</div>
                <div class="overview-trend" :class="systemStats.responseTrend < 0 ? 'up' : 'down'">
                  <el-icon><ArrowUp v-if="systemStats.responseTrend < 0" /><ArrowDown v-else /></el-icon>
                  {{ Math.abs(systemStats.responseTrend) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-number">{{ systemStats.errorRate }}%</div>
                <div class="overview-label">错误率</div>
                <div class="overview-trend" :class="systemStats.errorTrend < 0 ? 'up' : 'down'">
                  <el-icon><ArrowUp v-if="systemStats.errorTrend < 0" /><ArrowDown v-else /></el-icon>
                  {{ Math.abs(systemStats.errorTrend) }}%
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 性能图表 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>系统负载趋势</span>
              </template>
              <div class="chart-container">
                <v-chart 
                  :option="loadChartOption" 
                  style="height: 300px; width: 100%;"
                  autoresize
                />
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>内存使用情况</span>
              </template>
              <div class="chart-container">
                <v-chart 
                  :option="memoryChartOption" 
                  style="height: 300px; width: 100%;"
                  autoresize
                />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 服务器状态 -->
        <el-tab-pane label="服务器状态" name="server">
          <div class="tab-content">
            <el-table :data="serverStatus" stripe>
              <el-table-column prop="name" label="服务器名称" width="150" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'online' ? 'success' : 'danger'">
                    {{ row.status === 'online' ? '在线' : '离线' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="cpu" label="CPU使用率" width="120">
                <template #default="{ row }">
                  <el-progress 
                    :percentage="row.cpu" 
                    :color="getProgressColor(row.cpu)"
                    :stroke-width="8"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="memory" label="内存使用率" width="120">
                <template #default="{ row }">
                  <el-progress 
                    :percentage="row.memory" 
                    :color="getProgressColor(row.memory)"
                    :stroke-width="8"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="disk" label="磁盘使用率" width="120">
                <template #default="{ row }">
                  <el-progress 
                    :percentage="row.disk" 
                    :color="getProgressColor(row.disk)"
                    :stroke-width="8"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="uptime" label="运行时间" width="150" />
              <el-table-column prop="lastCheck" label="最后检查" width="180" />
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 数据库状态 -->
        <el-tab-pane label="数据库状态" name="database">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>数据库连接</span>
                  </template>
                  <div class="db-stats">
                    <div class="db-stat-item">
                      <span class="label">活跃连接：</span>
                      <span class="value">{{ dbStats.activeConnections }}</span>
                    </div>
                    <div class="db-stat-item">
                      <span class="label">最大连接：</span>
                      <span class="value">{{ dbStats.maxConnections }}</span>
                    </div>
                    <div class="db-stat-item">
                      <span class="label">查询次数：</span>
                      <span class="value">{{ dbStats.queryCount }}</span>
                    </div>
                    <div class="db-stat-item">
                      <span class="label">慢查询：</span>
                      <span class="value">{{ dbStats.slowQueries }}</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>数据库大小</span>
                  </template>
                  <div class="db-size">
                    <div class="size-item">
                      <span class="table-name">用户表</span>
                      <span class="table-size">2.5 MB</span>
                    </div>
                    <div class="size-item">
                      <span class="table-name">商品表</span>
                      <span class="table-size">15.8 MB</span>
                    </div>
                    <div class="size-item">
                      <span class="table-name">订单表</span>
                      <span class="table-size">8.2 MB</span>
                    </div>
                    <div class="size-item">
                      <span class="table-name">库存表</span>
                      <span class="table-size">3.1 MB</span>
                    </div>
                    <div class="size-item total">
                      <span class="table-name">总计</span>
                      <span class="table-size">29.6 MB</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 错误日志 -->
        <el-tab-pane label="错误日志" name="errors">
          <div class="tab-content">
            <div class="error-filters">
              <el-form :model="errorFilters" inline>
                <el-form-item label="错误级别">
                  <el-select v-model="errorFilters.level" placeholder="请选择级别" clearable>
                    <el-option label="严重" value="error" />
                    <el-option label="警告" value="warn" />
                    <el-option label="信息" value="info" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="errorFilters.dateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="filterErrors">
                    <el-icon><Search /></el-icon>
                    筛选
                  </el-button>
                  <el-button @click="clearErrorFilters">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table :data="filteredErrors" stripe>
              <el-table-column prop="time" label="时间" width="180" />
              <el-table-column prop="level" label="级别" width="100">
                <template #default="{ row }">
                  <el-tag :type="getErrorLevelType(row.level)">
                    {{ getErrorLevelText(row.level) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="message" label="错误信息" min-width="300" />
              <el-table-column prop="source" label="来源" width="150" />
              <el-table-column prop="user" label="用户" width="120" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewErrorDetail(row)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 性能分析 -->
        <el-tab-pane label="性能分析" name="performance">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card>
                  <template #header>
                    <span>页面加载时间</span>
                  </template>
                  <div class="performance-list">
                    <div class="perf-item">
                      <span class="page-name">仪表板</span>
                      <span class="load-time">1.2s</span>
                    </div>
                    <div class="perf-item">
                      <span class="page-name">用户管理</span>
                      <span class="load-time">0.8s</span>
                    </div>
                    <div class="perf-item">
                      <span class="page-name">商品管理</span>
                      <span class="load-time">1.5s</span>
                    </div>
                    <div class="perf-item">
                      <span class="page-name">订单管理</span>
                      <span class="load-time">2.1s</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card>
                  <template #header>
                    <span>API响应时间</span>
                  </template>
                  <div class="performance-list">
                    <div class="perf-item">
                      <span class="api-name">GET /api/users</span>
                      <span class="response-time">120ms</span>
                    </div>
                    <div class="perf-item">
                      <span class="api-name">POST /api/orders</span>
                      <span class="response-time">250ms</span>
                    </div>
                    <div class="perf-item">
                      <span class="api-name">GET /api/products</span>
                      <span class="response-time">180ms</span>
                    </div>
                    <div class="perf-item">
                      <span class="api-name">PUT /api/inventory</span>
                      <span class="response-time">300ms</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card>
                  <template #header>
                    <span>资源使用情况</span>
                  </template>
                  <div class="resource-usage">
                    <div class="resource-item">
                      <span class="resource-name">JavaScript</span>
                      <el-progress :percentage="45" :stroke-width="6" />
                    </div>
                    <div class="resource-item">
                      <span class="resource-name">CSS</span>
                      <el-progress :percentage="25" :stroke-width="6" />
                    </div>
                    <div class="resource-item">
                      <span class="resource-name">图片</span>
                      <el-progress :percentage="30" :stroke-width="6" />
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 错误详情对话框 -->
    <el-dialog
      v-model="errorDetailVisible"
      title="错误详情"
      width="800px"
    >
      <div v-if="currentError">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="时间">{{ currentError.time }}</el-descriptions-item>
          <el-descriptions-item label="级别">
            <el-tag :type="getErrorLevelType(currentError.level)">
              {{ getErrorLevelText(currentError.level) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="来源">{{ currentError.source }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentError.user }}</el-descriptions-item>
          <el-descriptions-item label="错误信息" :span="2">{{ currentError.message }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider>错误堆栈</el-divider>
        <pre class="error-stack">{{ currentError.stack }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, GaugeChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册必要的组件
use([
  CanvasRenderer,
  LineChart,
  GaugeChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 响应式数据
const activeTab = ref('server')
const errorDetailVisible = ref(false)
const currentError = ref(null)

// 系统统计
const systemStats = reactive({
  onlineUsers: 156,
  userTrend: 12.5,
  totalRequests: 12580,
  requestTrend: 8.3,
  avgResponseTime: 245,
  responseTrend: -15.2,
  errorRate: 0.8,
  errorTrend: -25.0
})

// 服务器状态
const serverStatus = ref([
  {
    name: 'Web服务器',
    status: 'online',
    cpu: 45,
    memory: 62,
    disk: 38,
    uptime: '15天 8小时',
    lastCheck: '2024-01-15 14:30:00'
  },
  {
    name: '数据库服务器',
    status: 'online',
    cpu: 28,
    memory: 45,
    disk: 52,
    uptime: '15天 8小时',
    lastCheck: '2024-01-15 14:30:00'
  },
  {
    name: '缓存服务器',
    status: 'online',
    cpu: 15,
    memory: 23,
    disk: 12,
    uptime: '15天 8小时',
    lastCheck: '2024-01-15 14:30:00'
  }
])

// 数据库统计
const dbStats = reactive({
  activeConnections: 25,
  maxConnections: 100,
  queryCount: 12580,
  slowQueries: 12
})

// 错误日志
const errors = ref([
  {
    id: 1,
    time: '2024-01-15 14:25:30',
    level: 'error',
    message: '数据库连接超时',
    source: 'DatabaseService',
    user: 'admin',
    stack: 'Error: Connection timeout\n    at DatabaseService.connect (database.js:45)\n    at async UserService.getUsers (user.js:23)'
  },
  {
    id: 2,
    time: '2024-01-15 14:20:15',
    level: 'warn',
    message: '内存使用率过高',
    source: 'SystemMonitor',
    user: 'system',
    stack: 'Warning: Memory usage above 80%\n    at SystemMonitor.checkMemory (monitor.js:67)'
  },
  {
    id: 3,
    time: '2024-01-15 14:15:45',
    level: 'info',
    message: '用户登录成功',
    source: 'AuthService',
    user: 'zhangsan',
    stack: 'Info: User login successful\n    at AuthService.login (auth.js:89)'
  }
])

// 错误筛选
const errorFilters = reactive({
  level: '',
  dateRange: []
})

// 计算属性
const filteredErrors = computed(() => {
  let filtered = errors.value
  
  if (errorFilters.level) {
    filtered = filtered.filter(error => error.level === errorFilters.level)
  }
  
  if (errorFilters.dateRange && errorFilters.dateRange.length === 2) {
    const [startTime, endTime] = errorFilters.dateRange
    filtered = filtered.filter(error => {
      return error.time >= startTime && error.time <= endTime
    })
  }
  
  return filtered
})

// 图表配置
const loadChartOption = computed(() => {
  const hours = []
  const cpuData = []
  const memoryData = []
  
  for (let i = 0; i < 24; i++) {
    hours.push(`${i}:00`)
    cpuData.push(Math.floor(Math.random() * 100))
    memoryData.push(Math.floor(Math.random() * 100))
  }
  
  return {
    title: {
      text: '24小时系统负载',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['CPU使用率', '内存使用率'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: 'value',
      max: 100
    },
    series: [
      {
        name: 'CPU使用率',
        type: 'line',
        smooth: true,
        data: cpuData,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '内存使用率',
        type: 'line',
        smooth: true,
        data: memoryData,
        itemStyle: { color: '#67C23A' }
      }
    ]
  }
})

const memoryChartOption = computed(() => {
  return {
    title: {
      text: '内存使用情况',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    series: [
      {
        name: '内存使用率',
        type: 'gauge',
        center: ['50%', '60%'],
        radius: '80%',
        min: 0,
        max: 100,
        splitNumber: 10,
        axisLine: {
          lineStyle: {
            width: 8,
            color: [
              [0.3, '#67C23A'],
              [0.7, '#E6A23C'],
              [1, '#F56C6C']
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          distance: -30,
          splitNumber: 5,
          lineStyle: {
            width: 2,
            color: '#999'
          }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: {
            width: 4,
            color: '#999'
          }
        },
        axisLabel: {
          color: 'auto',
          distance: 40,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}%',
          color: 'auto',
          fontSize: 20
        },
        data: [
          {
            value: 62
          }
        ]
      }
    ]
  }
})

// 方法
const handleTabChange = (tabName) => {
  activeTab.value = tabName
}

const refreshData = () => {
  ElMessage.success('数据已刷新')
  // 这里应该重新获取数据
}

const exportReport = () => {
  ElMessage.success('报告导出成功')
  // 这里应该实现报告导出逻辑
}

const getProgressColor = (percentage) => {
  if (percentage < 50) return '#67C23A'
  if (percentage < 80) return '#E6A23C'
  return '#F56C6C'
}

const filterErrors = () => {
  // 筛选逻辑已在计算属性中处理
}

const clearErrorFilters = () => {
  Object.assign(errorFilters, {
    level: '',
    dateRange: []
  })
}

const viewErrorDetail = (error) => {
  currentError.value = error
  errorDetailVisible.value = true
}

const getErrorLevelType = (level) => {
  const typeMap = {
    error: 'danger',
    warn: 'warning',
    info: 'info'
  }
  return typeMap[level] || 'info'
}

const getErrorLevelText = (level) => {
  const textMap = {
    error: '严重',
    warn: '警告',
    info: '信息'
  }
  return textMap[level] || '未知'
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.monitor-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.overview-section {
  margin-bottom: 30px;
}

.overview-section h4 {
  margin-bottom: 20px;
  color: #303133;
}

.overview-card {
  text-align: center;
}

.overview-content {
  padding: 20px 0;
}

.overview-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.overview-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.overview-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.overview-trend.up {
  color: #67C23A;
}

.overview-trend.down {
  color: #F56C6C;
}

.charts-section {
  margin-bottom: 30px;
}

.chart-container {
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.tab-content {
  margin-top: 20px;
}

.db-stats {
  padding: 20px 0;
}

.db-stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.db-stat-item:last-child {
  border-bottom: none;
}

.db-stat-item .label {
  color: #606266;
}

.db-stat-item .value {
  font-weight: bold;
  color: #303133;
}

.db-size {
  padding: 20px 0;
}

.size-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 8px 0;
}

.size-item.total {
  border-top: 1px solid #e4e7ed;
  padding-top: 12px;
  font-weight: bold;
}

.table-name {
  color: #606266;
}

.table-size {
  color: #303133;
}

.error-filters {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.performance-list {
  padding: 20px 0;
}

.perf-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.perf-item:last-child {
  border-bottom: none;
}

.page-name, .api-name {
  color: #606266;
}

.load-time, .response-time {
  font-weight: bold;
  color: #303133;
}

.resource-usage {
  padding: 20px 0;
}

.resource-item {
  margin-bottom: 20px;
}

.resource-name {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.error-stack {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #333;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
